package com.kx.center.controller;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.kx.center.entity.Channel;
import com.kx.center.entity.ScTrade;
import com.kx.center.entity.elm.ElmOrder;
import com.kx.center.entity.mt.MtTrade;
import com.kx.center.entity.query.QueryResult;
import com.kx.center.entity.query.QueryTrade;
import com.kx.center.enumerate.MessageCode;
import com.kx.center.service.StoreAppAccountService;
import com.kx.center.service.TradeService;
import com.kx.center.service.elm.ElmOrderService;
import com.kx.center.service.mt.MtTradeService;
import com.kx.center.util.DateUtil;
import com.kx.center.util.HttpClientUtil;
import com.kx.center.util.JSONParser;
import com.kx.center.util.Response;

@Controller
@RequestMapping("/trade")
public class TradeController {

	@Autowired
	TradeService tradeService;
	@Autowired
	StoreAppAccountService accountService;
	@Autowired
	MtTradeService mtTradeServcie;
	@Autowired
	ElmOrderService elmOrderService;
	
	
	//提供给美团推送订单所访问的url
	@RequestMapping(value = "mtPushOrder", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String mtPushOrder(HttpServletRequest request) throws Exception {

		HashMap<String, Object> data = new HashMap<String, Object>();

		Enumeration<?> pNames = request.getParameterNames();
		while (pNames.hasMoreElements()) {
			String name = (String) pNames.nextElement();
			String value = URLDecoder.decode(request.getParameter(name),
					"UTF-8");
			data.put(name, value);
			System.out.println(name + "=" + value);
		}

		Integer mtStoreId = mtTradeServcie.saveMtTrade(data);
		tradeService.mtSaveScTrade(data);

		//动态推送
		accountService.sendJpush(mtStoreId,"mt");
		
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("data", "ok");
		String json = JSONParser.stringify(map);
		return json;
	}

	//提供给美团取消订单所访问的url
	@RequestMapping(value = "mtCancelOrder", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String mtCancelOrder(HttpServletRequest request) throws Exception {

		Enumeration<?> pNames = request.getParameterNames();
		while (pNames.hasMoreElements()) {
			String name = (String) pNames.nextElement();
			String value = URLDecoder.decode(request.getParameter(name),
					"UTF-8");
			System.out.println(name + "=" + value);
		}

		String orderId = request.getParameter("order_id");
		String timestamp = request.getParameter("timestamp");

		
		
		MtTrade mtTrade = new MtTrade();
		mtTrade.setOrderId(Integer.parseInt(orderId));
		mtTrade.setUtime(Integer.parseInt(timestamp));
		mtTrade.setStatus(9);
		mtTradeServcie.updateMtTradeStatus(mtTrade);

		ScTrade scTrade = tradeService.findScTradeById(2, Long.parseLong(orderId));
		scTrade.setOuterId(orderId);
		scTrade.setUtime(DateUtil.unixTimeToTimestamp(Long.parseLong(timestamp)));
		scTrade.setOrderState(2);
		scTrade.setRefundState(2);
		scTrade.setRefundAmount(scTrade.getOrderAmount());
		tradeService.updateScTradeState(scTrade);
		
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("data", "ok");
		String json = JSONParser.stringify(map);
		return json;
	}
	
	//提供给饿了么推送订单所访问的url
	@RequestMapping(value = "elmPush", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String getElmPush(HttpServletRequest request) throws Exception {
		
		String timestamp = request.getParameter("timestamp");
		String consumer_key = request.getParameter("consumer_key");
		String push_action = request.getParameter("push_action");
		
		Map<String, String> maps = new HashMap<String, String>();
		maps.put("consumer_key", consumer_key);
		maps.put("timestamp", timestamp.toString());
		
		if (Integer.parseInt(push_action) == 1) {
			String eleme_order_ids = request.getParameter("eleme_order_ids");
			String s[] = eleme_order_ids.split(",");
			for (String order_id : s) {
				Channel channel = tradeService.findSecretByKey(Long.parseLong(consumer_key));
				String order_url = "http://v2.openapi.ele.me/order/" + order_id
						+ "/";
				String orderSig = HttpClientUtil.genSig(order_url, maps,
						channel.getAppSecret());
				String order_params = "&consumer_key=" + consumer_key + "&sig="
						+ orderSig + "&timestamp=" + timestamp + "";
				String orderjson = HttpClientUtil.sendGet(order_url,
						order_params);
				Integer elmId = elmOrderService.saveElmOrder(orderjson);
				
				tradeService.elmSaveScTrade(orderjson);
				//动态推送
				accountService.sendJpush(elmId,"elm");
			}
		}

		if (Integer.parseInt(push_action) == 2) {
			
			ElmOrder elmOrder = new ElmOrder();
			String new_status = request.getParameter("new_status");
			String eleme_order_id = request.getParameter("eleme_order_id");
			elmOrder.setStatusCode(Integer.parseInt(new_status));
			elmOrder.setOrderId(eleme_order_id);
			elmOrderService.updateElmOrderStatus(elmOrder);
			
			ScTrade scTrade = tradeService.findScTradeById(1, Long.parseLong(eleme_order_id));
			scTrade.setOuterId(eleme_order_id);
			scTrade.setUtime(DateUtil.unixTimeToTimestamp(Long.parseLong(timestamp)));
			scTrade.setRefundState(2);
			scTrade.setOrderState(2);
			scTrade.setRefundAmount(scTrade.getOrderAmount());
			tradeService.updateScTradeState(scTrade);
		}

		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("message", "ok");
		String json = JSONParser.stringify(map);
		return json;
	}

	// 查询订单销售汇总
	@RequestMapping(value = "storeSaleSummary", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String tradeSaleSummary(HttpServletRequest request)
			throws JsonProcessingException {

		Integer storeId, channelId;
		String json = "";

		channelId = NumberUtils.toInt(request.getParameter("channelId"));
		storeId = NumberUtils.toInt(request.getParameter("storeId"));

		if (storeId < 0 || channelId < 0) {
			return Response.error(MessageCode.NO_DATA);
		} else {
			json = tradeService.getTradeJson(storeId);
		}
		return json;
	}

	// 查询订单详情
	@RequestMapping(value = "storeTradeDetailList", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String getTradeDetailList(HttpServletRequest request) {

		Integer page, pageSize, channelId, status, storeId;

		QueryTrade queryTrade = new QueryTrade();
		List<Integer> orderState = new ArrayList<Integer>();
		List<Integer> refundState = new ArrayList<Integer>();
		
		String sortBy = request.getParameter("sortBy");
		String sortMethod = request.getParameter("sortMethod");

		channelId = NumberUtils.toInt(request.getParameter("channelId"));
		storeId = NumberUtils.toInt(request.getParameter("storeId"));
		status = NumberUtils.toInt(request.getParameter("status"));
		page = NumberUtils.toInt(request.getParameter("page"));
		pageSize = NumberUtils.toInt(request.getParameter("pageSize"));

		if (StringUtils.isBlank(sortBy))
			sortBy = "ctime";

		if (StringUtils.isBlank(sortMethod))
			sortMethod = "desc";
		
		queryTrade.setSortBy("ctime");
		queryTrade.setSortMethod("desc");
		queryTrade.setChannelId(channelId);
		queryTrade.setStoreId(storeId);
		queryTrade.setPage(page);
		queryTrade.setPageSize(pageSize);
		
		if(status == 1){
			orderState.add(1);
			refundState.add(0);
			queryTrade.setOrderState(orderState);
			queryTrade.setRefundState(refundState);
			
			QueryResult result = tradeService.queryTrade(queryTrade);
			
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("page", result.getPage());
			map.put("pageSize", result.getPageSize());
			map.put("totalRecord", result.getTotalRecord());
			map.put("data", result.getData());
			
			return Response.success(map);
		}
		
		if(status == 2){
			orderState.add(2);
			orderState.add(3);
			refundState.add(0);
			refundState.add(1);
			refundState.add(2);
			refundState.add(3);
			queryTrade.setOrderState(orderState);
			queryTrade.setRefundState(refundState);
			
			QueryResult result = tradeService.queryTrade(queryTrade);
			
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("page", result.getPage());
			map.put("pageSize", result.getPageSize());
			map.put("totalRecord", result.getTotalRecord());
			map.put("data", result.getData());
			
			return Response.success(map);
		}else{
			return Response.error(MessageCode.PARAMETER_WRONG);
		}

	}

	// 确认订单
	@RequestMapping(value = "confirm", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String getTradeConfirm(HttpServletRequest request) throws Exception {

		Long outerId;
		Integer channelId, confirmCode;
		String mtConfirmStatus, mtDeliveryStatus;

		outerId = Long.parseLong(request.getParameter("outerId"));
		channelId = Integer.parseInt(request.getParameter("channelId"));
		String orderState = request.getParameter("orderState");

		// 判断前台传输状态值
		if (orderState == "1" || Integer.parseInt(orderState) == 1) {

		} else {
			return Response.error(MessageCode.STATUS_ERROR);
		}

		ScTrade scTrade = tradeService.findScTradeById(channelId, outerId);
		MtTrade mtTrade = new MtTrade();
		ElmOrder elmOrder = new ElmOrder();
		
		if (scTrade != null && scTrade.getOrderState() == 1) {
			switch (channelId) {
			case 1:
				confirmCode = elmOrderService.sendConfirmStatusToElm(outerId);
				if(confirmCode == 200){
					scTrade.setOrderState(2);
					scTrade.setUtime(DateUtil.unixTimeToTimestamp(System.currentTimeMillis()/1000));
					scTrade.setOuterId(String.valueOf(outerId));
					tradeService.updateScTradeState(scTrade);
					
					elmOrder.setStatusCode(2);
					elmOrder.setOrderId(String.valueOf(outerId));
					elmOrderService.updateElmOrderStatus(elmOrder);
				}
				break;
			case 2:
				mtConfirmStatus = mtTradeServcie.sendConfirmToMt(outerId);
				mtDeliveryStatus = mtTradeServcie.sendDeliverToMt(outerId);
				if(mtConfirmStatus.equals("ok") && mtDeliveryStatus.equals("ok")){
					scTrade.setOrderState(2);
					scTrade.setUtime(DateUtil.unixTimeToTimestamp(System.currentTimeMillis()/1000));
					scTrade.setOuterId(String.valueOf(outerId));
					tradeService.updateScTradeState(scTrade);
					
					mtTrade.setWmOrderIdView(String.valueOf(outerId));
					mtTrade.setStatus(6);
					mtTradeServcie.updateMtTradeStatus(mtTrade);
				}else{
					return Response.error("操作失败");
				}
				break;
			}
		}else{
			return Response.error(MessageCode.STATUS_ERROR);
		}
		
		return Response.success("确认订单成功");
	}
	
	// 判断前台提交退款订单
	@RequestMapping(value = "refund", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String getTradeRefund(HttpServletRequest request) throws Exception {
		
		Long outerId;
		Integer channelId, cancelCode;
		String mtCancelStatus = null;
		
		outerId = Long.parseLong(request.getParameter("outerId"));
		channelId = Integer.parseInt(request.getParameter("channelId"));
		String orderState = request.getParameter("orderState");
		
		// 判断前台传输状态值
		if (orderState == "2" || Integer.parseInt(orderState) == 2) {

		} else {
			return Response.error(MessageCode.STATUS_ERROR);
		}
		
		ScTrade scTrade = tradeService.findScTradeById(channelId, outerId);
		MtTrade mtTrade = new MtTrade();
		ElmOrder elmOrder = new ElmOrder();
		
		if (scTrade != null && scTrade.getOrderState() == 2) {
			switch (channelId) {
			case 1:
				cancelCode = elmOrderService.sendInvalidStatusToElm(outerId);
				if(cancelCode == 200){
					scTrade.setRefundState(2);
					scTrade.setOuterId(String.valueOf(outerId));
					scTrade.setUtime(DateUtil.unixTimeToTimestamp(System.currentTimeMillis()/1000));
					tradeService.updateScTradeState(scTrade);
					
					elmOrder.setStatusCode(-1);
					elmOrder.setOrderId(String.valueOf(outerId));
					elmOrderService.updateElmOrderStatus(elmOrder);
				}else{
					return Response.success("退款失败,请联系美团外卖客服!");
				}
				break;
			case 2:
				mtCancelStatus = mtTradeServcie.sendAgreeRefundToMt(outerId);
				if(mtCancelStatus.equals("ok")){
					scTrade.setRefundState(2);
					scTrade.setOuterId(String.valueOf(outerId));
					scTrade.setUtime(DateUtil.unixTimeToTimestamp(System.currentTimeMillis()/1000));
					scTrade.setRefundAmount(scTrade.getOrderAmount());
					tradeService.updateScTradeState(scTrade);
					
					mtTrade.setWmOrderIdView(String.valueOf(outerId));
					mtTrade.setStatus(9);
					mtTradeServcie.updateMtTradeStatus(mtTrade);
				}else{
					return Response.success("退款失败,请联系美团外卖客服!");
				}
				break;
			}
		}else{
			return Response.error(MessageCode.STATUS_ERROR);
		}
		return Response.success("退款成功");
	}
	
}
